package com.douyang.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.douyang.mapper.VideoUploadCacheMapper;
import com.douyang.pojo.VideoUploadCache;
import com.douyang.service.VideoUploadCacheService;
import com.douyang.utils.MinioUtil;
import com.douyang.base.expcetion.VideoException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaoma
 * @since 2025-02-28
 */
@Service
public class VideoUploadCacheServiceImpl extends ServiceImpl<VideoUploadCacheMapper, VideoUploadCache> implements VideoUploadCacheService {
    @Autowired
    private MinioUtil minioUtil;


    @Override
    public Boolean checkChunkExist(String chunkMd5,String fileMd5) {
        return lambdaQuery()
                .eq(VideoUploadCache::getChunkMd5,chunkMd5)
                .eq(VideoUploadCache::getFileMd5,fileMd5)
                .count() > 0;
    }

    @Override
    public String uploadChunk(MultipartFile chunk, String chunkMd5,String fileMd5){
        try {
            //上传前校验
            if(!DigestUtils.md5DigestAsHex(chunk.getInputStream()).equals(chunkMd5)){
                throw new RuntimeException("文件校验失败");
            }
            //上传，完成后再次校验
            boolean b = minioUtil.updateChunkFile(chunk, chunkMd5,fileMd5);
            if(!b)throw new RuntimeException("文件校验失败");
        }catch (Exception e){
            throw new VideoException("文件上传失败，请尝试，具体原因："+e.getMessage());
        }

        VideoUploadCache videoUploadCache = VideoUploadCache.builder()
                .chunkMd5(chunkMd5)
                .fileMd5(fileMd5)
                .build();
        save(videoUploadCache);
        return "ok";
    }

    @Override
    public void mergeChunk(String fileMd5) {


        List<VideoUploadCache> videoUploadCacheList = lambdaQuery()
//                .select(VideoUploadCache::getChunkMd5)
//                TODO 加上报空异常？？
                .eq(VideoUploadCache::getFileMd5, fileMd5)
                .list();


        if(videoUploadCacheList.isEmpty()){throw new VideoException("mergeChunk:分块未上传");}

        List<String> chunkMd5ListByFileMd5 = videoUploadCacheList
                .stream()
                .map(VideoUploadCache::getChunkMd5)
                .toList();
        try {
            minioUtil.mergeChunk(chunkMd5ListByFileMd5, fileMd5, ".mp4");
        }catch (Exception e){
            throw new VideoException(e.getMessage());
        }

    }
}
